﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.Account;
using ManagementApi.Models.Auth;
using ManagementApi.Models.Project;
using ManagementApi.Models.System.Menu;
using ManagementApi.Models.User;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Options;
using ManagementApi.Services;
using ManagementApi.Services.Authentication;
using ManagementApi.TreeParty.SMS;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Modules;
using Modules.Commander;
using Modules.Constructor;
using Modules.Corp;
using Modules.Manager;
using Modules.Project;
using Modules.Project.Entitys;
using Modules.SMS;
using Modules.System.Menu;
using Modules.System.Security;
using Modules.System.Settings;
using Modules.System.Settings.Entitys;
using Modules.System.User;
using PmSoft;
using PmSoft.Entity;
using PmSoft.Exceptions;
using PmSoft.Utilities;
using System.ComponentModel.DataAnnotations;

namespace ManagementApi.Controllers
{
    /// <summary>
    /// 认证相关业务接口
    /// </summary>
    [Route("/api/v1/auth")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly UserAuthenticationService authenticationService;
        private readonly ProjectService projectService;
        private readonly ManagementApplicationContext applicationContext;
        private readonly UserService userSevice;
        private readonly MenuService menuService;
        private readonly IConfiguration configuration;
        private readonly CaptchaService captchaService;
        private readonly CorpService corpService;
        private readonly IMemoryCache memoryCache;
        private readonly IMapper mapper;
        private readonly ConstructorService constructorService;
        private static List<VerifyCodeCache> verifyCodeCaches = new List<VerifyCodeCache>();
        private readonly ManagerService managerService;
        private readonly CommanderService commanderService;
        private readonly SecurityService securityService;
        private readonly SmsSendLogService smsSendLogService;
        private readonly ISMSService sMSService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="authenticationService"></param>
        /// <param name="captchaService"></param>
        /// <param name="userSevice"></param>
        /// <param name="menuService"></param>
        /// <param name="projectService"></param>
        /// <param name="applicationContext"></param>
        /// <param name="configuration"></param>
        /// <param name="corpService"></param>
        /// <param name="memoryCache"></param>
        /// <param name="mapper"></param>
        /// <param name="constructorService"></param>
        /// <param name="managerService"></param>
        /// <param name="commanderService"></param>
        public AuthController(UserAuthenticationService authenticationService,
                CaptchaService captchaService,
                UserService userSevice,
              MenuService menuService,
              ProjectService projectService,
              ManagementApplicationContext applicationContext,
              IConfiguration configuration,
              CorpService corpService,
              IMemoryCache memoryCache,
              IMapper mapper,
              ConstructorService constructorService,
              ManagerService managerService,
              CommanderService commanderService,
              SecurityService securityService,
              SmsSendLogService smsSendLogService,
              ISMSService sMSService
              )
        {
            this.authenticationService = authenticationService;
            this.userSevice = userSevice;
            this.menuService = menuService;
            this.projectService = projectService;
            this.applicationContext = applicationContext;
            this.configuration = configuration;
            this.captchaService = captchaService;
            this.corpService = corpService;
            this.memoryCache = memoryCache;
            this.mapper = mapper;
            this.constructorService = constructorService;
            this.managerService = managerService;
            this.commanderService = commanderService;
            this.securityService = securityService;
            this.smsSendLogService = smsSendLogService;
            this.sMSService = sMSService;
        }

        #region 验证码

        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <param name="codeType">验证码类型 0：纯数字 1：数字+字母 2：数字运算 默认1</param>
        /// <returns></returns>
        [HttpGet("captcha")]
        public ApiResult<VerifyCodeResult> Captcha(string codeType = "1")
        {
            string uuid = Guid.NewGuid().ToString().Replace("-", "");
            var codeInfo = new VerifyCode();
            if (codeType == "1")
            {
                codeInfo = captchaService.CreateVerifyCode(4, VerifyCodeType.CHAR);
            }
            else if (codeType == "2")
            {
                codeInfo = captchaService.CreateVerifyCode(4, VerifyCodeType.ARITH);
            }
            else if (codeType == "0")
            {
                codeInfo = captchaService.CreateVerifyCode(4, VerifyCodeType.NUM);
            }
            VerifyCodeCache dic = new VerifyCodeCache()
            {
                Id = uuid,
                Code = codeInfo.Code
            };

            verifyCodeCaches.Add(dic);
            VerifyCodeResult verifyCodeResult = new VerifyCodeResult()
            {
                Id = uuid,
                Base64Str = codeInfo.Base64Str
            };
            return ApiResult<VerifyCodeResult>.Success(verifyCodeResult);
        }

        /// <summary>
        /// 检查验证码是否有效
        /// </summary>
        /// <param name="verifyCodeCache"></param>
        /// <returns></returns>
        [HttpPut("captcha_verify")]
        public ApiResult Check(VerifyCodeCache verifyCodeCache)
        {
            var index = verifyCodeCaches.FindIndex(m =>
            {
                if (m.Id.Equals(verifyCodeCache.Id) && m.Code.ToLower().Equals(verifyCodeCache.Code.ToLower()))
                {
                    return true;
                }

                return false;
            });

            if (index >= 0)
            {
                verifyCodeCaches.RemoveAt(index);
                return ApiResult.Success("验证成功");
            }
            else
                return ApiResult.Failure("验证失败");
        }

        #endregion 验证码

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public ApiResult<LoginResult> Login(UserLoginForm form)
        {
            var index = verifyCodeCaches.FindIndex(m =>
            {
                if (m.Id.Equals(form.Id) && m.Code.ToLower().Equals(form.Code.ToLower()))
                {
                    return true;
                }

                return false;
            });

            if (index >= 0)
            {
                verifyCodeCaches.RemoveAt(index);
                var loginResult = authenticationService.SignIn(form);
                return ApiResult<LoginResult>.Success(loginResult);
            }
            else
                return ApiResult<LoginResult>.Failure("验证码错误");
        }

        /// <summary>
        /// 验证用户名存在的角色
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet("verifyusername_login/{userName}")]
        public ApiResult<IEnumerable<LabelValue<UserType>>> GetLoginRolesByUserName(string userName, string password)
        {
            List<LabelValue<UserType>> roles = new();

            RetrievePasswordSetting passwordSetting = SettingManager<RetrievePasswordSetting>.Instance.Get();
            SysUser? sysUser = userSevice.GetUser(userName);
            if (sysUser != null && securityService.VerifyPassword(password, sysUser.SecurityId)) roles.Add(new LabelValue<UserType>()
            {
                Label = "主管单位",
                Value = UserType.SysUser,
            });
            CorpInfo? corpInfo = corpService.GetCorpInfo(userName);
            if (corpInfo != null && securityService.VerifyPassword(password, corpInfo.SecurityId)) roles.Add(new LabelValue<UserType>()
            {
                Label = "企业",
                Value = UserType.Corp,
            });
            ConstructorInfo? constructorInfo = constructorService.GetConstructorInfo(userName);
            if (constructorInfo != null && securityService.VerifyPassword(password, constructorInfo.SecurityId)) roles.Add(new LabelValue<UserType>()
            {
                Label = "建设单位",
                Value = UserType.Constructor,
            });
            ManagerInfo? managerInfo = managerService.GetManagerInfo(userName);
            if (managerInfo != null && securityService.VerifyPassword(password, managerInfo.SecurityId)) roles.Add(new LabelValue<UserType>()
            {
                Label = "项目管理员",
                Value = UserType.Manager,
            });
            CommanderInfo? commanderInfo = commanderService.GetCommanderInfo(userName);
            if (commanderInfo != null && securityService.VerifyPassword(password, commanderInfo.SecurityId)) roles.Add(new LabelValue<UserType>()
            {
                Label = "指挥部",
                Value = UserType.Commander,
            });
            return ApiResult<IEnumerable<LabelValue<UserType>>>.Success(roles);
        }

        /// <summary>
        /// 通过用户名获取短信验证码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        [HttpGet("verificationcode/{userName}")]
        public ApiResult GetSMSVerificationCode(string userName, UserType userType)
        {
            string phone = string.Empty;
            switch (userType)
            {
                case UserType.SysUser:
                    phone = userSevice.GetUser(userName)?.Mobile ?? string.Empty; break;
                case UserType.Constructor:
                    phone = constructorService.GetConstructorInfo(userName)?.LinkTel ?? string.Empty; break;
                case UserType.Corp:
                    phone = corpService.GetCorpInfo(userName)?.LinkTel ?? string.Empty; break;
                case UserType.Manager:
                    phone = managerService.GetManagerInfo(userName)?.Mobile ?? string.Empty; break;
                case UserType.Commander:
                    phone = commanderService.GetCommanderInfo(userName)?.Mobile ?? string.Empty; break;
                default:
                    break;
            }
            if (string.IsNullOrWhiteSpace(phone))
                return ApiResult.Failure("用户未预留手机号");

            string code = SmsBuidler.Instance().GetValidateCode();
            SmsModel smsModel = SmsBuidler.Instance().ValidateCode(code);
            smsModel.Code = code;
            //发送验证码
            applicationContext.GetService<SmsSendLogService>().Send(phone, smsModel);
            return ApiResult.Success("验证码发送成功");
        }

        /// <summary>
        /// 验证用户名存在的角色
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpGet("verifyusername/{userName}")]
        public ApiResult<IEnumerable<LabelValue<UserType>>> GetLoginRolesByUserName(string userName)
        {
            List<LabelValue<UserType>> roles = new();

            RetrievePasswordSetting passwordSetting = SettingManager<RetrievePasswordSetting>.Instance.Get();
            SysUser? sysUser = userSevice.GetUser(userName);
            if (sysUser != null) roles.Add(new LabelValue<UserType>()
            {
                Label = "主管单位",
                Value = UserType.SysUser,
                Extend1 = sysUser.Mobile.AsEncryptedPhone(),
                Extend2 = passwordSetting.SysUserContent
            });
            CorpInfo? corpInfo = corpService.GetCorpInfo(userName);
            if (corpInfo != null) roles.Add(new LabelValue<UserType>()
            {
                Label = "企业",
                Value = UserType.Corp,
                Extend1 = corpInfo.LinkTel.AsEncryptedPhone(),
                Extend2 = passwordSetting.CorpContent
            });
            ConstructorInfo? constructorInfo = constructorService.GetConstructorInfo(userName);
            if (constructorInfo != null) roles.Add(new LabelValue<UserType>()
            {
                Label = "建设单位",
                Value = UserType.Constructor,
                Extend1 = constructorInfo.LegalMobile.AsEncryptedPhone(),
                Extend2 = passwordSetting.ConstructorContent
            });
            ManagerInfo? managerInfo = managerService.GetManagerInfo(userName);
            if (managerInfo != null) roles.Add(new LabelValue<UserType>()
            {
                Label = "项目管理员",
                Value = UserType.Manager,
                Extend1 = managerInfo.Mobile.AsEncryptedPhone(),
                Extend2 = passwordSetting.ManagerContent
            });
            CommanderInfo? commanderInfo = commanderService.GetCommanderInfo(userName);
            if (commanderInfo != null) roles.Add(new LabelValue<UserType>()
            {
                Label = "指挥部",
                Value = UserType.Commander,
                Extend1 = commanderInfo.Mobile.AsEncryptedPhone(),
                Extend2 = passwordSetting.CommanderContent
            });
            return ApiResult<IEnumerable<LabelValue<UserType>>>.Success(roles);
        }

        /// <summary>
        /// 审核失败的项目重新提交审核
        /// </summary>
        /// <returns></returns>
        [HttpPut("failprojectresubmit")]
        public ApiResult UpdateProject(ProjectEditForm form)
        {
            string token = memoryCache.Get<string>(form.EditToken) ?? throw new BusinessException($"token失效,请重新登录操作");
            var tokens = token.Split("_");
            List<int> tokenInts = ValueUtility.ParseInt(tokens);
            if (tokenInts.Count != 2)
            {
                throw new BusinessException($"token错误,请重新登录操作");
            }
            var projectInfo = projectService.GetProjectInfo(tokenInts[0]) ?? throw new BusinessException("项目信息不存在");
            if (projectInfo.ManagerId != tokenInts[1]) throw new BusinessException("登录用户无该项目权限");
            if (projectInfo.AuditStatus == ProjectConstants.项目审核状态.通过) throw new BusinessException("改项目已审核通过不能编辑");
            mapper.Map(form, projectInfo);

            var supervisorCorp = corpService.GetCorpInfo(projectInfo.SupervisorCorpId ?? 0) ?? new CorpInfo()
            {
                Name = form.SupervisorCorpName ?? string.Empty,
                Code = form.SupervisorCorpCode ?? string.Empty,
                Type = ConstructorType.企业,
                CorpType = 企业分类.工程监理
            };

            List<ProjectAttachment> projectAttachments = new();

            foreach (var item in form.Attachments)
            {
                projectAttachments.Add(new ProjectAttachment()
                {
                    Id = Guid.NewGuid().ToString().Replace("-", ""),
                    AttachmentId = item,
                    ObjectId = projectInfo.ProjectId.ToString(),
                    Tenant = 项目附件租户.Project,
                    AttachmentType = 附件类型.中标通知书,
                    CreateTime = DateTime.Now
                });
            }
            if (!form.HasSupervisor)
            {
                foreach (var item in form.NoSupervisorAttachments)
                {
                    projectAttachments.Add(new ProjectAttachment()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = projectInfo.ProjectId.ToString(),
                        Tenant = 项目附件租户.Project,
                        AttachmentType = 附件类型.无监理证明,
                        CreateTime = DateTime.Now
                    });
                }
            }
            if (projectInfo.PositionCount > 1)
            {
                foreach (var item in form.PositionAttachments)
                {
                    projectAttachments.Add(new ProjectAttachment()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = projectInfo.ProjectId.ToString(),
                        Tenant = 项目附件租户.Project,
                        AttachmentType = 附件类型.多地施工证明,
                        CreateTime = DateTime.Now
                    });
                }
            }
            if (projectInfo.HasEarnestMoney.HasValue && projectInfo.HasEarnestMoney.Value)
            {
                foreach (var item in form.EarnestAttachments)
                {
                    projectAttachments.Add(new ProjectAttachment()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = projectInfo.ProjectId.ToString(),
                        Tenant = 项目附件租户.Project,
                        AttachmentType = 附件类型.担保文件,
                        CreateTime = DateTime.Now
                    });
                }
            }
            else
            {
                projectInfo.HasEarnestMoney = false;
                projectInfo.EarnestEndDate = null;
                projectInfo.EarnestMoney = 0;
                projectInfo.EarnestStartDate = null;
                projectInfo.EarnestUnitCode = null;
                projectInfo.EarnestUnitName = null;
            }
            projectInfo.AuditStatus = ProjectConstants.项目审核状态.待审核;
            projectService.UpdateProjectInfo(projectInfo, supervisorCorp, form.SupervisorCorpAmount ?? 0, form.CommanderId, projectAttachments);
            memoryCache.Remove(form.EditToken);
            return ApiResult.Success("编辑成功,请等待审核");
        }

        /// <summary>
        /// </summary>
        /// <param name="editToken"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        [HttpGet("failproject/{editToken}/form")]
        public ApiResult<ProjectRegisterForm> GetProjectForm(string editToken)
        {
            string token = memoryCache.Get<string>(editToken) ?? throw new BusinessException($"token失效,请重新登录操作");
            var tokens = token.Split("_");
            List<int> tokenInts = ValueUtility.ParseInt(tokens);
            if (tokenInts.Count != 2)
            {
                throw new BusinessException($"token错误,请重新登录操作");
            }
            var projectInfo = projectService.GetProjectInfo(tokenInts[0]) ?? throw new BusinessException("项目信息不存在");
            if (projectInfo.ManagerId != tokenInts[1]) throw new BusinessException("登录用户无该项目权限");
            if (projectInfo.AuditStatus == ProjectConstants.项目审核状态.通过) throw new BusinessException("该项目已审核通过不能编辑");
            if (projectInfo.AuditStatus == ProjectConstants.项目审核状态.待审核) throw new BusinessException("该项目正在审核不能编辑");
            var projectRegisterForm = new ProjectRegisterForm();
            projectRegisterForm.ProjectId = projectInfo.ProjectId;
            var corpService = ServiceAccessor.GetService<CorpService>();
            if (projectInfo.LumpContractorCorpId != null)
            {
                var lumpContractorCorp = corpService.GetCorpInfo((int)projectInfo.LumpContractorCorpId);
                if (lumpContractorCorp != null)
                {
                    projectRegisterForm.LumpContractorCorpId = lumpContractorCorp.CorpId;
                    projectRegisterForm.LumpContractorCorpName = lumpContractorCorp.Name;
                    projectRegisterForm.LumpContractorCorpCode = lumpContractorCorp.Code;
                }
            }
            projectRegisterForm.AuditReason = projectInfo.AuditReason;
            projectInfo.LumpContractorCorpPhoneNum = projectInfo.LumpContractorCorpPhoneNum;
            return ApiResult<ProjectRegisterForm>.Success(projectRegisterForm);
        }

        #region 完善信息

        /// <summary>
        /// 完善建设单位信息
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("constructorLogin")]
        public ApiResult<LoginResult> ConstructorLogin(ConstructorEditForm form)
        {
            if (string.IsNullOrEmpty(form.VerificationCode))
                return ApiResult<LoginResult>.Failure("短信验证码不能为空");

            if (!smsSendLogService.Validate(form.LinkTel, form.VerificationCode, MsgType.VerificationCode))
                return ApiResult<LoginResult>.Failure("短信验证码错误或已过期");
            var loginResult = authenticationService.ConstructorSignIn(form);
            return ApiResult<LoginResult>.Success(loginResult);
        }

        /// <summary>
        /// 完善企业信息
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("corpLogin")]
        public ApiResult<LoginResult> CorpLogin(CorpEditForm form)
        {
            if (string.IsNullOrEmpty(form.VerificationCode))
                return ApiResult<LoginResult>.Failure("短信验证码不能为空");

            if (!smsSendLogService.Validate(form.LinkTel, form.VerificationCode, MsgType.VerificationCode))
                return ApiResult<LoginResult>.Failure("短信验证码错误或已过期");
            var loginResult = authenticationService.CorpSignIn(form);
            return ApiResult<LoginResult>.Success(loginResult);
        }

        /// <summary>
        /// 查询企业信息
        /// </summary>
        /// <param name="editToken"></param>
        /// <returns></returns>
        [HttpGet("getCorp/{editToken}")]
        public ApiResult<CorpCreateForm> GetCorp(string editToken)
        {
            string? code = memoryCache.Get<string>(editToken);
            if (code == null)
                return ApiResult<CorpCreateForm>.Failure($"企业登录信息不存在，请先登录后完善信息");
            CorpInfo? corpInfo = corpService.GetCorpInfo(code);
            return ApiResult<CorpCreateForm>.Success(mapper.Map<CorpCreateForm>(corpInfo));
        }

        /// <summary>
        /// 查询建设单位信息
        /// </summary>
        /// <param name="editToken"></param>
        /// <returns></returns>
        [HttpGet("getConstructor/{editToken}")]
        public ApiResult<ConstructorCreateForm> GetConstructor(string editToken)
        {
            string? code = memoryCache.Get<string>(editToken);
            if (code == null)
                return ApiResult<ConstructorCreateForm>.Failure($"建设单位登录信息不存在，请先登录后完善信息");
            ConstructorInfo? constructorInfo = constructorService.GetConstructorInfo(code);
            return ApiResult<ConstructorCreateForm>.Success(mapper.Map<ConstructorCreateForm>(constructorInfo));
        }

        #endregion 完善信息

        /// <summary>
        /// 退出登陆
        /// </summary>
        /// <returns></returns>
        [HttpPost("logout")]
        public ApiResult Logout()
        {
            return ApiResult.Success("退出成功");
        }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("me")]
        [Authorize]
        public ApiResult<LoginUserInfoDto> GetUserLoginInfo()
        {
            var loginUser = applicationContext.CurrentUser;
            if (loginUser == null)
                return ApiResult<LoginUserInfoDto>.Failure("未获取到登录信息");
            if (loginUser is SysUser sysUser)
            {
                var perms = sysUser.GetMenus().Where(m => !string.IsNullOrEmpty(m.Perm)).Select(m => m.Perm).ToList();
                var roleCodes = sysUser.GetRoles().Select(m => m.Code).ToList();
                return ApiResult<LoginUserInfoDto>.Success(LoginUserInfoDto.Builder(sysUser, roleCodes, perms));
            }
            else if (loginUser is DeptUser deptUser)
            {
                var user = userSevice.GetUser(deptUser.Id);
                if (user == null)
                    return ApiResult<LoginUserInfoDto>.Failure("未获取到登录信息");
                var perms = user.GetMenus().Where(m => !string.IsNullOrEmpty(m.Perm)).Select(m => m.Perm);
                var roleCodes = user.GetRoles().Select(m => m.Code);
                return ApiResult<LoginUserInfoDto>.Success(LoginUserInfoDto.Builder(user, roleCodes, perms));
            }
            else if (loginUser is CorpInfo corpInfo)
            {
                ProjectInfo? projectInfo = projectService.GetProjectInfo(corpInfo.ProjectId);
                var result = LoginUserInfoDto.Builder(corpInfo);
                result.Project = projectInfo;

                return ApiResult<LoginUserInfoDto>.Success(result);
            }
            else if (loginUser is ConstructorInfo constructor)
            {
                ProjectInfo? projectInfo = projectService.GetProjectInfo(constructor.ProjectId);
                var result = LoginUserInfoDto.Builder(constructor);
                result.Project = projectInfo;
                return ApiResult<LoginUserInfoDto>.Success(result);
            }
            else if (loginUser is ManagerInfo manager)
            {
                ProjectInfo? projectInfo = projectService.GetProjectInfo(manager.ProjectId);
                var result = LoginUserInfoDto.Builder(manager);
                result.Project = projectInfo;
                return ApiResult<LoginUserInfoDto>.Success(result);
            }
            else if (loginUser is CommanderInfo commander)
            {
                ProjectInfo? projectInfo = projectService.GetProjectInfo(commander.ProjectId);
                var result = LoginUserInfoDto.Builder(commander);
                result.Project = projectInfo;
                return ApiResult<LoginUserInfoDto>.Success(result);
            }
            else
                return ApiResult<LoginUserInfoDto>.Failure("未知登录用户类型");
        }

        /// <summary>
        /// 当前登陆用户的-路由列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("routes")]
        [Authorize]
        public ApiResult<IEnumerable<RouteDto>> GetRoutes()
        {
            UserType? loginType = applicationContext.CurrentUser?.Type;
            if (loginType == null)
                throw new ArgumentNullException(nameof(loginType));

            IEnumerable<RouteDto>? routes = null;
            switch (loginType)
            {
                case UserType.SysUser:
                    routes = menuService.GetAllMenus().AsRoutes();//系统用户则获取系统定制路由
                    break;

                default://其他类型用户从配置文件获取路由
                    var userRouters = configuration.GetSection("UserRoutes").Get<List<UserRouter>>();
                    routes = userRouters?.FirstOrDefault(m => m.Type == loginType)?.Routes;
                    break;
            }
            if (routes == null)
                routes = new List<RouteDto>();
            return ApiResult<IEnumerable<RouteDto>>.Success(routes);
        }

        /// <summary>
        /// 刷新token
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost("refresh_token")]
        public async Task<ApiResult<LoginResult>> RefreshTokenAsync()
        {
            if (applicationContext.CurrentUser == null)
                return ApiResult<LoginResult>.Failure("获取用户信息失败");

            LoginResult result = new();
            DateTime expires = DateTime.Now.AddMinutes(15);
            string token = await authenticationService.RefreshTokenAsync(applicationContext.CurrentUser, expires);
            if (string.IsNullOrEmpty(token))
                return ApiResult<LoginResult>.Failure("刷新失败");

            result.TokenType = JwtBearerDefaults.AuthenticationScheme;
            result.Expires = (long)expires.Subtract(DateTime.Now).TotalMilliseconds;
            result.AccessToken = token;

            return ApiResult<LoginResult>.Success(result);
        }
    }
}